using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace newtelligence.DasBlog.Web.Core
{
	/// <summary>
	/// Summary description for TitleHandler.
	/// </summary>
	public class TitleMapperModule : IHttpModule
	{
		static readonly string[] HttpHandlerStrings = new string[] {"CaptchaImage.aspx", "aggbug.ashx", "blogger.aspx", "pingback.aspx", "trackback.aspx", "get_aspx_ver.aspx"};
		private EventHandler onBeginRequest;
		static readonly Regex regex = new Regex( @"(?<Year>(?:\d{4}))/(?<Month>\d{1,2})/(?<Day>\d{1,2})", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); 

		public TitleMapperModule()
		{
			onBeginRequest = new EventHandler(this.HandleBeginRequest);
		}

		public void Init(HttpApplication context)
		{
			SiteConfig config = SiteConfig.GetSiteConfig();
			if (config.EnableTitlePermaLink == true)
			{
				context.BeginRequest += onBeginRequest;
			}
		}

		public void Dispose()
		{
		}

		private void HandleBeginRequest( object sender, EventArgs evargs )
		{
			HttpApplication app = sender as HttpApplication;
			string requestUrl = "";

			if ( app != null )
			{
				requestUrl = app.Context.Request.Url.PathAndQuery;
			
				if (requestUrl.IndexOf(",") == -1 & requestUrl.IndexOf("?") == -1 )
				{
					// TODO: there has to be a way to also see if the request is from an HttpHander since File.Exists won't work.
					if (requestUrl.EndsWith(".aspx") && !File.Exists(app.Context.Server.MapPath(app.Context.Request.FilePath)))
					{
						string title = app.Context.Request.Url.Segments[app.Context.Request.Url.Segments.Length - 1];

						if (Array.IndexOf(HttpHandlerStrings, title) == -1 )
						{
							title = title.Replace(".aspx", "");
							title = title.Replace("+", "");
							title = title.Replace(" ", "");
							title = title.Replace("%2b", "");

							string path = app.Context.Request.Url.LocalPath;
							DateTime dateTime = DateTime.MinValue;
							// try and get date
							
							Match match = regex.Match(path);
							if (match.Groups.Count == 4)
							{
								int year = Convert.ToInt32(match.Groups["Year"].Value);
								int month = Convert.ToInt32(match.Groups["Month"].Value);
								int day = Convert.ToInt32(match.Groups["Day"].Value);

								dateTime = new DateTime(year, month, day, 0, 0, 0);

								if (dateTime != DateTime.MinValue)
								{
									requestUrl = String.Format("~/Permalink.aspx?title={0}&date={1}", title, dateTime.ToString("yyyy-MM-dd"));
									app.Context.RewritePath(requestUrl);
								}
							}
							else
							{
								requestUrl = "Permalink.aspx?title=" + title;
								app.Context.RewritePath(requestUrl);
							}

//							ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
//							IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
//
//							Entry entry = dataService.GetEntry( title );
//							if ( entry != null )
//							{
//								requestUrl = "Permalink.aspx?guid=" + entry.EntryId;
//								app.Context.RewritePath(requestUrl);
//							}
						}
					}
				}
			}
		}
	}
}
